package wpmp.portal.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import wcommons.httputils.RequestUtils;
import wcommons.httputils.ResponseUtils;
import wcommons.httputils.quickbean.RespInfo;
import wcommons.lang.quickbean.Message;
import wpmp.portal.service.UserService;
import wpmp.security.client.internal.SecurityUtils;
import wpmp.utils.quickbean.UserView;

/**
 * @author Wayne.Wang<5waynewang@gmail.com>
 * @since 11:49:16 AM Dec 5, 2013
 */
@Controller
@RequestMapping("/logout.do")
public class LogoutController extends BaseController {

	@Autowired
	private UserService service;

	@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
	public void logout(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		final String securityId = SecurityUtils.getSecurityId(req);
		if (StringUtils.isBlank(securityId)) {
			ResponseUtils.renderJson(resp, Message.getDefaultMessageString());
			return;
		}

		final String remoteIp = RequestUtils.getRemoteIp(req);

		final UserView userView = this.getUserView(req, securityId);
		if (userView != null) {
			final String loginName = userView.getUser().getLoginName();
			final RespInfo<Object> respInfo;
			try {
				respInfo = service.logout(loginName, securityId);
			}
			catch (Exception e) {
				log.error("Error to logout by [" + loginName + ", " + securityId + "] from [" + remoteIp + "]\r\n", e);
				ResponseUtils.renderJson(resp, Message.getDefaultMessageString());
				return;
			}
			if (respInfo == null) {
				ResponseUtils.renderJson(resp, Message.getDefaultMessageString());
				return;
			}

			if (respInfo.isSuccess()) {
				log.info("[{}] logout successfully from [{}]", loginName, remoteIp);
			}
			else {
				log.warn("[{}] is failed to logout from [{}] by [{}], RemoteResponse:[{}]", loginName, remoteIp,
						securityId, respInfo);
			}
		}
		this.removeUserView(req);

		// 删除cookie中的密钥
		SecurityUtils.clearSecurityId(req, resp);
		req.getSession().invalidate();
		ResponseUtils.renderJson(resp, Message.getDefaultMessageString());
	}
}
